#include "dialog.h"
#include "ui_dialog.h"
#include "settings.h"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);

    ui->hostsListView->setModel(&hostsStringListModel);

    connect(ui->searchButton, &QPushButton::clicked, this, &Dialog::searchButtonClicked);

    connect(&discoveryService, &DiscoveryService::newHost, this, &Dialog::newHost);
    discoveryService.start(Settings::serverPort());
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::searchButtonClicked()
{
    QStringList l = hostsStringListModel.stringList();
    l.clear();
    endpoints.clear();
    hostsStringListModel.setStringList(l);
    discoveryService.refresh();
}

void Dialog::newHost(const QString &deviceName, const QHostAddress &addr, quint16 port)
{
    QStringList l = hostsStringListModel.stringList();
    if (port == 0)
    {
        for (int i = 0; i < endpoints.size(); ++i)
        {
            if (endpoints[i].addr.isEqual(addr))
            {
                endpoints.removeAt(i);
                l.removeAt(i);
                hostsStringListModel.setStringList(l);
                return;
            }
        }
        return;
    }
    for (int i = 0; i < endpoints.size(); ++i)
    {
        if (endpoints[i].addr.isEqual(addr))
        {
            if (l.at(i) != deviceName)
            {
                l.replace(i, deviceName);
                hostsStringListModel.setStringList(l);
            }
            endpoints[i].port = port;
            return;
        }
    }
    endpoints.append({addr, port});
    l.append(deviceName);
    hostsStringListModel.setStringList(l);
}
